﻿using FuelAbp.Inputs;
using FuelDXApplication1.Entity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Client;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace FuelAbp.DataServer
{
    /// <summary>
    /// 用户数据服务
    /// </summary>
    [ApiExplorerSettings(GroupName = "v2")]
    public class UserDataService: ApplicationService
    {
       private readonly ISqlSugarClient db;
        public UserDataService(ISqlSugarClient db)
        {
            this.db = db;
        }
        /// <summary>
        /// 128位处理key 
        /// </summary>
        /// <param name="keyArray">原字节</param>
        /// <param name="key">处理key</param>
        /// <returns></returns>
        private static byte[] GetAesKey(byte[] keyArray, string key)
        {
            byte[] newArray = new byte[16];
            if (keyArray.Length < 16)
            {
                for (int i = 0; i < newArray.Length; i++)
                {
                    if (i >= keyArray.Length)
                    {
                        newArray[i] = 0;
                    }
                    else
                    {
                        newArray[i] = keyArray[i];
                    }
                }
            }
            return newArray;
        }
        /// <summary>
        /// 使用AES加密字符串,按128位处理key
        /// </summary>
        /// <param name="content">加密内容</param>
        /// <param name="key">秘钥，需要128位、256位.....</param>
        /// <returns>Base64字符串结果</returns>
        public static string AesEncrypt(string content, string key, bool autoHandle = true)
        {
            byte[] keyArray = Encoding.UTF8.GetBytes(key);
            if (autoHandle)
            {
                keyArray = GetAesKey(keyArray, key);
            }
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(content);
            SymmetricAlgorithm des = Aes.Create();
            des.Key = keyArray;
            des.Mode = CipherMode.ECB;
            des.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = des.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray);
        }
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<UnitiveResult<int>> AddAccount(AddAccountInputDto input)
        {
            var res = ObjectMapper.Map<AddAccountInputDto, Account>(input);
            res.Password = AesEncrypt(res.Password, "2562352");
            var us = await db.Queryable<Account>().FirstAsync(it => it.UserName == input.UserName);
            if (us!=null) 
            {
                return UnitiveResult<int>.Error(message: "用户已存在");
            }
            var list =await db.Insertable(res).ExecuteCommandAsync();
            if (list>0)
            {
                return UnitiveResult<int>.Success(list);
            } 
            else
            { 
                return UnitiveResult<int>.Error(message: "注册失败");
            }
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        ///<param name="input">用户登录请求</param>
        /// <returns>返回登录结果</returns>
        public async Task<dynamic> UserLogin(LoginInput input)
        {
            input.Password = AesEncrypt(input.Password, "2562352");
            var list = await db.Queryable<Account>().Where(x => x.UserName == input.UserName && x.Password == input.Password).FirstAsync();
            if (list != null) return UnitiveResult<string>.Success("登录成功");
            return (UnitiveResult<string>.Error(message: "用户名或密码错误"));
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <returns>获取用户信息</returns>
        public async Task<UnitiveResult<List<Account>>> GetAccounts(int pageIndex,int pageSize)
        {
            RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
            var list=await  db.Queryable<Account>().ToPageListAsync(pageIndex, pageSize, total);
            return UnitiveResult<List<Account>>.Success(list);
        }
        public void Main(string[] args)
        {
            //实例化一个发送邮件类。
            MailMessage mailMessage = new MailMessage();
            //发件人邮箱地址，方法重载不同，可以根据需求自行选择。
            mailMessage.From = new MailAddress("1701985033@qq.com");
            //收件人邮箱地址。
            mailMessage.To.Add(new MailAddress("2966066399@qq.com"));
            //抄送人邮箱地址。
            //message.CC.Add(sender);
            //邮件标题。
            mailMessage.Subject = "数据错误";
            //邮件内容。
            mailMessage.Body = "你都一个数据发生错误！";
            //是否支持内容为HTML。
            //mailMessage.IsBodyHtml = true;
            //实例化一个SmtpClient类。
            SmtpClient client = new SmtpClient();
            client.Port = 587;
            //在这里使用的是qq邮箱，所以是smtp.qq.com，如果你使用的是126邮箱，那么就是smtp.126.com。
            //client.Host = "smtp.163.com";
            client.Host = "smtp.qq.com";
            //使用安全加密连接（是否启用SSL）
            client.EnableSsl = true;
            //设置超时时间
            //client.Timeout = 10000;
            //不和请求一块发送。
            client.UseDefaultCredentials = false;
            //验证发件人身份(发件人的邮箱，邮箱里的生成授权码);
            client.Credentials = new NetworkCredential("1701985033@qq.com", "dbgcsrfvyhquiead");//szcodirtgvjgbfii
            //网易邮箱客户端授权码DJURBEKTXEWXQATX
            //client.Credentials = new NetworkCredential("liulijun3236@163.com", "ZAJDNCKWHUBHQIMY");
            try
            {
                //发送
                client.Send(mailMessage);
                //发送成功
            }
            catch (Exception)//发送异常
            {
                //发送失败
                //System.IO.File.WriteAllText(@"C:\test.txt", e.ToString(), Encoding.UTF8);
            }
        }
    }
}
